import sys
import os
import datetime

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database

class FeeGenerator:
    def __init__(self):
        self.db = Database()
    
    def generate_fee(self, dormitory_id, fee_type, amount, due_days=30):
        """
        为指定宿舍生成费用账单
        
        参数:
            dormitory_id (int): 宿舍ID
            fee_type (str): 费用类型（如水费、电费、住宿费等）
            amount (float): 费用金额
            due_days (int): 缴费期限天数，默认30天
        
        返回:
            bool: 生成成功返回True，否则返回False
        """
        try:
            # 验证输入
            if not dormitory_id or not fee_type or amount is None:
                print("错误：所有必填字段都必须填写")
                return False
            
            try:
                dormitory_id = int(dormitory_id)
                amount = float(amount)
                if amount <= 0:
                    print("错误：金额必须大于0")
                    return False
            except ValueError:
                print("错误：宿舍ID必须是整数，金额必须是数字")
                return False
            
            # 连接数据库
            self.db.connect()
            
            # 检查宿舍是否存在
            self.db.cursor.execute(
                "SELECT building, room_number FROM dormitory WHERE id = ?",
                (dormitory_id,)
            )
            dormitory = self.db.cursor.fetchone()
            if not dormitory:
                print(f"错误：ID为 {dormitory_id} 的宿舍不存在")
                self.db.close()
                return False
            
            building, room_number = dormitory
            
            # 生成账单日期和到期日期
            billing_date = datetime.datetime.now().strftime("%Y-%m-%d")
            due_date = (datetime.datetime.now() + datetime.timedelta(days=due_days)).strftime("%Y-%m-%d")
            
            # 插入费用记录
            self.db.cursor.execute(
                "INSERT INTO fee (dormitory_id, fee_type, amount, billing_date, due_date, payment_status) VALUES (?, ?, ?, ?, ?, ?)",
                (dormitory_id, fee_type, amount, billing_date, due_date, "unpaid")
            )
            self.db.conn.commit()
            
            fee_id = self.db.cursor.lastrowid
            print(f"成功：为宿舍 {building}-{room_number} 生成{fee_type}账单，金额：{amount}元，到期日：{due_date}")
            return fee_id
        except Exception as e:
            print(f"错误：生成费用账单时发生错误 - {str(e)}")
            return False
        finally:
            self.db.close()
    
    def generate_batch_fee(self, fee_type, amount_per_person, due_days=30):
        """
        为所有宿舍批量生成费用账单（按人数计算总费用）
        
        参数:
            fee_type (str): 费用类型（如水费、电费、住宿费等）
            amount_per_person (float): 每人费用金额
            due_days (int): 缴费期限天数，默认30天
        
        返回:
            int: 成功生成的账单数量
        """
        try:
            # 验证输入
            if not fee_type or amount_per_person is None:
                print("错误：所有必填字段都必须填写")
                return 0
            
            try:
                amount_per_person = float(amount_per_person)
                if amount_per_person <= 0:
                    print("错误：金额必须大于0")
                    return 0
            except ValueError:
                print("错误：金额必须是数字")
                return 0
            
            # 连接数据库
            self.db.connect()
            
            # 获取所有宿舍信息
            self.db.cursor.execute(
                "SELECT id, building, room_number, current_count FROM dormitory WHERE status = 'available'"
            )
            dormitories = self.db.cursor.fetchall()
            
            if not dormitories:
                print("没有找到可用的宿舍")
                self.db.close()
                return 0
            
            # 生成账单日期和到期日期
            billing_date = datetime.datetime.now().strftime("%Y-%m-%d")
            due_date = (datetime.datetime.now() + datetime.timedelta(days=due_days)).strftime("%Y-%m-%d")
            
            # 批量生成账单
            count = 0
            for dormitory in dormitories:
                dormitory_id, building, room_number, current_count = dormitory
                
                # 只为有人居住的宿舍生成账单
                if current_count > 0:
                    # 计算总费用（每人费用 * 人数）
                    total_amount = amount_per_person * current_count
                    
                    # 插入费用记录
                    self.db.cursor.execute(
                        "INSERT INTO fee (dormitory_id, fee_type, amount, billing_date, due_date, payment_status) VALUES (?, ?, ?, ?, ?, ?)",
                        (dormitory_id, fee_type, total_amount, billing_date, due_date, "unpaid")
                    )
                    count += 1
                    print(f"为宿舍 {building}-{room_number} 生成{fee_type}账单，金额：{total_amount}元，到期日：{due_date}")
            
            self.db.conn.commit()
            print(f"成功：共为 {count} 个宿舍生成{fee_type}账单")
            return count
        except Exception as e:
            print(f"错误：批量生成费用账单时发生错误 - {str(e)}")
            return 0
        finally:
            self.db.close()

# 如果直接运行此文件，提供命令行界面
if __name__ == "__main__":
    generator = FeeGenerator()
    
    print("===== 宿舍费用账单生成 =====")
    print("1. 为单个宿舍生成费用账单")
    print("2. 批量生成费用账单（按人数计算）")
    
    choice = input("请选择操作 (1-2): ")
    
    if choice == '1':
        try:
            dormitory_id = input("请输入宿舍ID: ")
            fee_type = input("请输入费用类型（如水费、电费、住宿费）: ")
            amount = input("请输入费用金额: ")
            due_days = input("请输入缴费期限天数（默认30天）: ") or 30
            
            generator.generate_fee(dormitory_id, fee_type, amount, int(due_days))
        except ValueError:
            print("错误：请输入有效的数值")
    
    elif choice == '2':
        try:
            fee_type = input("请输入费用类型（如水费、电费、住宿费）: ")
            amount_per_person = input("请输入每人费用金额: ")
            due_days = input("请输入缴费期限天数（默认30天）: ") or 30
            
            generator.generate_batch_fee(fee_type, amount_per_person, int(due_days))
        except ValueError:
            print("错误：请输入有效的数值")
    
    else:
        print("无效的选择")